package com.bupt.service;

import com.bupt.bean.ChannelCorrectionParam;
import com.bupt.bean.ChannelInterPoints;
import com.bupt.bean.DeviceChannel;
import com.bupt.config.CommonCode;
import com.bupt.config.CorrectionResult;
import com.bupt.dao.*;
import com.bupt.utils.DateUtils;
import com.bupt.vo.ChannelCorrectionParamVo;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class TemperatureService {

    @Autowired
    private SectionRepository sectionRepository;

    @Autowired
    private TemperatureRepository temperatureRepository;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private DeviceChannelRepository deviceChannelRepository;

    @Autowired
    private ChannelInterPointsRepository channelInterPointsRepository;

    @Autowired
    private ChannelCorrectionParamRepository channelCorrectionParamRepository;

    @Autowired
    private PrimaryKeyService primaryKeyService;

    public Map<String, List> getAreaTheAgeTemperature() {
        //总集合
        HashMap<String, List> map = new HashMap<>();
        //存放时间集合
        ArrayList<String> hourList = new ArrayList<>();
        ArrayList<String> endhourList = new ArrayList<>();
        //存放分区集合
        ArrayList<String> areaList = new ArrayList<>();
        ArrayList<String> areaIdList = new ArrayList<>();
        //存放平均温度集合
        ArrayList<List> temperatureList = new ArrayList<>();
        ArrayList<String> temperatureOneHoursList = new ArrayList<>();
        //获取当下前4个小时的日期  2021-08-25 17
        String oneHourAgo = DateUtils.getPastHoursDate(1);
        String twoHourAgo = DateUtils.getPastHoursDate(2);
        String threeHourAgo = DateUtils.getPastHoursDate(3);
        String fourHourAgo = DateUtils.getPastHoursDate(4);
        String nowHour = DateUtils.getPastHoursDate(0);
        hourList.add(fourHourAgo);
        hourList.add(threeHourAgo);
        hourList.add(twoHourAgo);
        hourList.add(oneHourAgo);
        endhourList.add(fourHourAgo.substring(11, 13) + ":00");
        endhourList.add(threeHourAgo.substring(11, 13) + ":00");
        endhourList.add(twoHourAgo.substring(11, 13) + ":00");
        endhourList.add(oneHourAgo.substring(11, 13) + ":00");
        map.put("hourList", endhourList);

        //获取所有分区名称和分区索引
        List<Map<String, Object>> allArea = sectionRepository.findAllArea();
        for (int i = 0; i < allArea.size(); i++) {
            areaList.add(allArea.get(i).get("section_name").toString());
            String section_index = allArea.get(i).get("section_index").toString();
            areaIdList.add(section_index);
            //通过每个分区索引获取1个小时内的平均温度值


        }
        //获取时间段 从小到大 相差一小时 1--2   2--3
        for (int i = 0; i < hourList.size(); i++) {
            String beginHour = hourList.get(i);
            String stopHour;
            if (i == hourList.size() - 1) {
                stopHour = nowHour;
            } else {
                stopHour = hourList.get(i + 1);
            }
            //获取某个时间段所有分区平均温度
            List<Map<String, Object>> avgTemperatureList = temperatureRepository.findAvgTemperature(beginHour, stopHour);
            //如果该时间段所有分区都没值,存入0 有值的话也循环判断一下吧 防止某个分区某个时间段没有值
            if (avgTemperatureList.size() > 0) {
                //temperatureOneHoursList=new ArrayList<>();
                for (int j = 0; j < areaIdList.size(); j++) {
                    for (int k = 0; k < avgTemperatureList.size(); k++) {
                        Object channel_section_id = avgTemperatureList.get(k).get("channel_section_id");
                        if (avgTemperatureList.get(k).get("channel_section_id").toString().equals(areaIdList.get(j))) {
                            temperatureOneHoursList.add(avgTemperatureList.get(k).get("avgtemperature").toString());
                            break;
                        } else {
                            if (k == avgTemperatureList.size() - 1) {
                                temperatureOneHoursList.add("0");
                            }
                        }
                    }
                }
            } else {
                for (int j = 0; j < areaList.size(); j++) {
                    temperatureOneHoursList.add("0");
                }
            }

        }
        //平均温度循环放入最终集合
        ArrayList<String> oneAreaList = new ArrayList<>();
        ArrayList<String> twoAreaList = new ArrayList<>();
        ArrayList<String> threeAreaList = new ArrayList<>();
        ArrayList<String> fourAreaList = new ArrayList<>();

        int a = 0;
        for (int i = 0; i < hourList.size(); i++) {
            oneAreaList.add(temperatureOneHoursList.get(a++));
            twoAreaList.add(temperatureOneHoursList.get(a++));
            threeAreaList.add(temperatureOneHoursList.get(a++));
            fourAreaList.add(temperatureOneHoursList.get(a++));
        }

        temperatureList.add(oneAreaList);
        temperatureList.add(twoAreaList);
        temperatureList.add(threeAreaList);
        temperatureList.add(fourAreaList);

        map.put("temperatureList", temperatureList);
        map.put("areaList", areaList);
        return map;
    }

    //温度修正数据
    public List<ChannelCorrectionParamVo> correctionByDeviceChannelId(Integer deviceChannelId) {
        String sql = "select ccp.*,d.device_name,d.device_id,dc.channel_index from channel_correction_param_t ccp,device_channel_t dc ,device_t d where ccp.device_channel_id=dc.device_channel_id and d.device_id=dc.device_id and ccp.device_channel_id="+deviceChannelId;
        Query query = entityManager.createNativeQuery(sql);
        List<ChannelCorrectionParamVo> channelCorrectionParamVoList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return channelCorrectionParamVoList;
    }

    //指定通道插点
    public CorrectionResult correctionAndInterAdd(Integer deviceChannelId,String temperature, String position) {
        //校验通道是否存在
        DeviceChannel deviceChannel = deviceChannelRepository.findByDeviceChannelId(deviceChannelId);
        if(deviceChannel==null){
            return new CorrectionResult(CommonCode.NOTEXISTFAIL,new ChannelCorrectionParam());
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        ChannelCorrectionParam channelCorrectionParam = new ChannelCorrectionParam();
        Integer channel_correction_param_id = primaryKeyService.getPrimaryKey("CHANNEL_CORRECTION_PARAM_ID");
        channelCorrectionParam.setChannelCorrectionParamId(channel_correction_param_id);
        channelCorrectionParam.setDeviceChannelId(deviceChannelId);
        channelCorrectionParam.setPosition(position);
        channelCorrectionParam.setTemperature(temperature);
//        channelCorrectionParam.setCoefficientA("a");
//        channelCorrectionParam.setCoefficientB("b");
//        channelCorrectionParam.setCoefficientDef("def");
        channelCorrectionParamRepository.save(channelCorrectionParam);

        ChannelInterPoints channelInterPoints = new ChannelInterPoints();
        Integer channel_inter_points_id = primaryKeyService.getPrimaryKey("CHANNEL_INTER_POINTS_ID");
        channelInterPoints.setChannelInterPointsId(channel_inter_points_id);
        channelInterPoints.setDeviceChannelId(deviceChannelId);
        channelInterPoints.setPosition(position);
        channelInterPoints.setTemperature(temperature);
        channelInterPoints.setCreateTime(timestamp);
        channelInterPointsRepository.save(channelInterPoints);

        CorrectionResult result = new CorrectionResult(CommonCode.SUCCESS, channelCorrectionParam);

        return result;
    }
}
